package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.example.demo.common.JwtUtils;
import com.example.demo.entity.User;
import com.example.demo.service.IUserService;
import com.example.demo.shiro.ShiroUtils;
import com.example.demo.shiro.SimpleHashUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author zhaiding
 * @since 2019/5/18
 */
@RestController
public class WebController extends ApiController {

    @Resource
    private IUserService userService;


    @PostMapping(value = "/login")
    public R login(@RequestBody User user) {
        User u = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (u == null) {
            throw new UnknownAccountException("No account found for admin [" + user.getUsername() + "]");
        }
        if (!SimpleHashUtil.simpleHash(user.getPwd()).equals(u.getPwd())) {
            throw new IncorrectCredentialsException();
        }
        return R.ok(JwtUtils.sign(user.getUsername()));
    }

    @GetMapping(value = "/logout")
    public R logout() {
        // 退出会自动清除缓存的权限
        ShiroUtils.logout();
        return success("logout");
    }


    @GetMapping(value = "/article")
    public R article() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return R.failed("You are already logged in");
        } else {
            return R.failed("You are guest");
        }
    }

    @GetMapping(value = "/require_auth")
    @RequiresPermissions("user:a")
    public R requireAuth() {
        return R.failed("You are authenticated");
    }

    @GetMapping(value = "/require_role")
    @RequiresRoles("admin")
    public R requireRole() {
        return R.failed("You are visiting require_role");
    }


}
